package de.velvettear.squirrel.gui;

import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import de.velvettear.squirrel.R;
import de.velvettear.squirrel.kernel.BruteForceReturn;
import de.velvettear.squirrel.kernel.Statics;
import de.velvettear.squirrel.util.BruteForceHelper;
import de.velvettear.squirrel.util.MessageHelper;
import de.velvettear.squirrel.util.TimeHelper;
import de.velvettear.squirrel.util.WLANHelper;

public class BruteForce extends Activity implements OnClickListener {

	private EditText et_minLength;
	private EditText et_maxLength;
	
	private TextView tv_password;
	private TextView tv_progress;
	private TextView tv_percentage;
	private ProgressBar progressBar;

	private String m_sTarget;
		
	private long maximumPossibilities;
	private int progressPercentage;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_bruteforce);
	    
	    if (getIntent().hasExtra(Statics.INTENT_BRUTEFORCE)) {
	    	m_sTarget = getIntent().getExtras().getString(Statics.INTENT_BRUTEFORCE);
	    }
	    
	    TextView tv_target = (TextView) findViewById(R.id.bruteforce_tv_target_value);
	    tv_target.setText(m_sTarget);
	    
	    tv_password = (TextView) findViewById(R.id.bruteforce_tv_password);
	    tv_progress = (TextView) findViewById(R.id.bruteforce_tv_progress);
	    tv_percentage = (TextView) findViewById(R.id.bruteforce_tv_percentage);
	    et_minLength = (EditText) findViewById(R.id.bruteforce_et_length_start);
	    et_maxLength = (EditText) findViewById(R.id.bruteforce_et_length_end);
	    
	    progressBar = (ProgressBar) findViewById(R.id.bruteforce_pb);
	    
	    Button btn_start = (Button) findViewById(R.id.bruteforce_btn_start);
	    btn_start.setOnClickListener(this);
	    
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.bruteforce_btn_start:								
			startBruteForceAttack();
			break;

		}
	}
		
	private void startBruteForceAttack() {
		BruteForceHelper.getBruteForceChars(true, true, true, false);
		maximumPossibilities = BruteForceHelper.getPossibilityCount(Integer.parseInt(et_maxLength.getText().toString()));
		progressBar.setProgress(0);
		progressBar.setMax(100);		
		tv_progress.setText("0 / " + maximumPossibilities);
		
		LinearLayout ll_progress = (LinearLayout) findViewById(R.id.bruteforce_ll_progress);
		ll_progress.setVisibility(View.VISIBLE);
		
		AsyncTask<Integer, Void, BruteForceReturn> bruteForceTask = new AsyncTask<Integer, Void, BruteForceReturn>() {

			@Override
			protected BruteForceReturn doInBackground(Integer... params) {
				long startTime = new Date().getTime();
				BruteForceReturn ret = new BruteForceReturn();
				boolean success = false;
				long tryCounter = 0;
				String m_sPassword = "";
				while (!success && tryCounter < maximumPossibilities) {
					tryCounter++;
					guiHandler.sendMessage(MessageHelper.createMessage(Statics.HANDLER_BRUTEFORCE, m_sPassword, String.valueOf(tryCounter)));
					success = WLANHelper.tryWifiPassword(m_sTarget, m_sPassword);
					if (success) {
						long endTime = new Date().getTime();
						ret.m_bSuccess = true;
						ret.m_sMessage = "Passwort gefunden!";
						ret.m_sCount = tryCounter + " / " + maximumPossibilities;
						ret.m_sDuration = TimeHelper.getDuration(startTime, endTime);
						ret.m_sPassword = m_sPassword;
						return ret;
					} else {
						m_sPassword = BruteForceHelper.next(m_sPassword);
					}
				}
				long endTime = new Date().getTime();
				ret.m_bSuccess = false;
				ret.m_sMessage = "Passwort nicht gefunden!";
				ret.m_sCount = tryCounter + " / " + maximumPossibilities;
				ret.m_sDuration = TimeHelper.getDuration(startTime, endTime);
				return ret;
			}
			
			@Override
			protected void onPostExecute(BruteForceReturn ret) {			
				Intent bruteForceResultIntent = new Intent(BruteForce.this, BruteForceResult.class);
				bruteForceResultIntent.putExtra(Statics.INTENT_BRUTEFORCERESULT, (Parcelable) ret);
				startActivity(bruteForceResultIntent);
			}

		};
		
		int min = 0;
		int max = 0;
		if (et_minLength.getText().toString() != null && !et_minLength.getText().toString().equals("")) {
			min = Integer.parseInt(et_minLength.getText().toString());
		}
		if (et_maxLength.getText().toString() != null && !et_maxLength.getText().toString().equals("")) {
			max = Integer.parseInt(et_maxLength.getText().toString());
		}
		
		bruteForceTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, min, max);
	}

	public Handler guiHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle data = msg.getData();
			if (data.containsKey(Statics.MESSAGE_BRUTEFORCE_PASSWORD)) {
				tv_password.setText(data.getString(Statics.MESSAGE_BRUTEFORCE_PASSWORD));
			}
			if (data.containsKey(Statics.MESSAGE_BRUTEFORCE_COUNT)) {
				long count = Long.parseLong(data.getString(Statics.MESSAGE_BRUTEFORCE_COUNT));
				tv_progress.setText(count + " / " + maximumPossibilities);
				
				int percentage = BruteForceHelper.getProgressPercentage(count, maximumPossibilities);
				tv_percentage.setText(String.valueOf(percentage) + "%");
				progressBar.setProgress(percentage);
			}
		}
	};

}
